import { openDB } from 'idb';

const DB_NAME = 'docDraftDB';
const STORE_NAME = 'drafts';

async function getDB() {
  return openDB(DB_NAME, 1, {
    upgrade(db) {
      if (!db.objectStoreNames.contains(STORE_NAME)) {
        db.createObjectStore(STORE_NAME, { keyPath: 'docId' });
      }
    },
  });
}

// localStorage 工具函数 - 专门用于文档草稿管理
export const draftStorage = {
    // 存储键前缀
    DRAFT_KEY_PREFIX: 'doc_detail_draft_',

    // 保存文档草稿
    async saveDraft(docId, draftData) {
        try {
            const db = await getDB();
            const data = {
                docId: this.DRAFT_KEY_PREFIX + docId,
                ...draftData,
                lastModified: new Date().toISOString()
            };
            await db.put(STORE_NAME, data);
            return true;
        } catch (error) {
            console.error('保存草稿失败:', error);
            return false;
        }
    },

    // 获取文档草稿
    async getDraft(docId) {
        try {
            const db = await getDB();
            const data = await db.get(STORE_NAME, this.DRAFT_KEY_PREFIX + docId);
            return data || null;
        } catch (error) {
            console.error('获取草稿失败:', error);
            return null;
        }
    },

    // 删除文档草稿
    async removeDraft(docId) {
        try {
            const db = await getDB();
            await db.delete(STORE_NAME, this.DRAFT_KEY_PREFIX + docId);
            return true;
        } catch (error) {
            console.error('删除草稿失败:', error);
            return false;
        }
    },

    // 检查是否有草稿
    async hasDraft(docId) {
        const db = await getDB();
        const data = await db.get(STORE_NAME, this.DRAFT_KEY_PREFIX + docId);
        return data !== undefined && data !== null;
    },

    // 获取所有草稿的文档ID
    async getAllDraftIds() {
        const db = await getDB();
        const all = await db.getAllKeys(STORE_NAME);
        return all
            .filter(key => key.startsWith(this.DRAFT_KEY_PREFIX))
            .map(key => key.replace(this.DRAFT_KEY_PREFIX, ''));
    },

    // 清理过期的草稿（7天前）
    async cleanExpiredDrafts() {
        const db = await getDB();
        const all = await db.getAll(STORE_NAME);
        const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
        for (const data of all) {
            if (data.lastModified && new Date(data.lastModified) < sevenDaysAgo) {
                await db.delete(STORE_NAME, data.docId);
                console.log(`清理过期草稿: ${data.docId}`);
            }
        }
    },

    // 清理所有草稿
    async cleanAllDrafts() {
        const db = await getDB();
        const all = await db.getAllKeys(STORE_NAME);
        for (const key of all) {
            if (key.startsWith(this.DRAFT_KEY_PREFIX)) {
                await db.delete(STORE_NAME, key);
            }
        }
    },

    // 获取草稿存储使用情况
    async getDraftStorageInfo() {
        const db = await getDB();
        const all = await db.getAll(STORE_NAME);
        let totalSize = 0;
        all.forEach(data => {
            totalSize += JSON.stringify(data).length;
        });
        return {
            draftCount: all.length,
            totalSize: totalSize,
            totalSizeKB: (totalSize / 1024).toFixed(2)
        };
    }
};

// 通用localStorage工具函数
export const storage = {
    // 设置数据
    set(key, value) {
        try {
            localStorage.setItem(key, JSON.stringify(value));
            return true;
        } catch (error) {
            console.error('localStorage set error:', error);
            return false;
        }
    },

    // 获取数据
    get(key, defaultValue = null) {
        try {
            const item = localStorage.getItem(key);
            return item ? JSON.parse(item) : defaultValue;
        } catch (error) {
            console.error('localStorage get error:', error);
            return defaultValue;
        }
    },

    // 删除数据
    remove(key) {
        try {
            localStorage.removeItem(key);
            return true;
        } catch (error) {
            console.error('localStorage remove error:', error);
            return false;
        }
    },

    // 清空所有数据
    clear() {
        try {
            localStorage.clear();
            return true;
        } catch (error) {
            console.error('localStorage clear error:', error);
            return false;
        }
    },

    // 检查是否有某个key
    has(key) {
        return localStorage.getItem(key) !== null;
    },

    // 获取所有key
    keys() {
        return Object.keys(localStorage);
    }
};

// 预定义的存储key
export const STORAGE_KEYS = {
    USER_PREFERENCES: 'user_preferences',
    EDITOR_SETTINGS: 'editor_settings',
    RECENT_DOCUMENTS: 'recent_documents',
    THEME_MODE: 'theme_mode',
    SIDEBAR_COLLAPSED: 'sidebar_collapsed'
};